package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional
    @Override
    public void saveSetmeal(SetmealDto setmealDTO) {
        // 套餐
        this.save(setmealDTO);

        // 套餐菜品关系
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        setmealDishList.forEach(
                setmealDish -> {
                    setmealDish.setSetmealId(setmealDTO.getId());
                }
        );
        setmealDishService.saveBatch(setmealDishList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeWithDish(List<Long> ids) {
        // 校验套餐状态是否
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getStatus, 1);
        wrapper.in(Setmeal::getId, ids);
        int count = count(wrapper);
        if(count > 0) {
            throw new CustomException("套餐在售，不能删除");
        }

        // 删除套餐
        removeByIds(ids);

        // 删除套餐菜品关系
        LambdaQueryWrapper<SetmealDish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(dishWrapper);
    }
}
